package com.bizihang.controller.async;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.Callable;

/**
 * @author 毕子航 951755883@qq.com
 * @date 2018/08/15
 */
@Slf4j
@RestController
@RequestMapping("/orders")
public class AsyncController {
	@Autowired
	MockQueue mockQueue;

	@Autowired
	DeferredResultHolder deferredResultHolder;

	@GetMapping(value = "/1")
	public Callable<String> getOne1() throws InterruptedException {
		log.info("主线程开始");
		Callable<String> callable = new Callable<String>() {
			@Override
			public String call() throws Exception {
				log.info("副线程开始");
				Thread.sleep(1000L);
				log.info("副线程返回");
				return "success";
			}
		};
		log.info("主线程返回");
		return callable;
	}


	@GetMapping(value = "/2")
	public DeferredResult<String> getOne2() {
		/*
		1.http请求->| 应用1 |					   |	|					| 应用2  |
					|       |					   |消息|<---3.监听消息队列-|	处	 |
					| 线程1	|-2发送创建订单的请求->|	|					|	理	 |
					|		|					   |队列|					|	请	 |
		6.Http响应->| 线程2	|-5.监听处理结果------>|	|<---4.发送处理结果-|	求	 |

		 */
		//0.主线程接收用户请求
		log.info("主线程1开始");

		//1.应用1：主线程（线程1）发送创建订单的请求->消息队列
		String orderNumber = RandomStringUtils.randomNumeric(8);
		mockQueue.setPlaceOrder(orderNumber);

		//2.线程2取回订单创建的处理结果
		DeferredResult<String> stringDeferredResult = new DeferredResult<>();
		deferredResultHolder.getMap().put(orderNumber, stringDeferredResult);
		log.info("主线程1返回");
		return stringDeferredResult;
	}
}
